<template>
  <div class="search-filter pop-bg">
    <div class="search-filter-header">
      <span>筛选</span>
      <span class="pointer" @click="close">
        <el-icon><Close /></el-icon>
      </span>
    </div>
    <div class="search-filter-body">
      <ul class="search-filter-list" v-show="searchOptions.condition.length">
        <li v-for="(item, index) in searchOptions.condition" :key="index">
          <template v-if="index === 0"> <div class="item dt">当</div> </template>
          <template v-else>
            <el-select
              class="item"
              v-model="item.logic"
              placeholder="请选择"
              @change="logicChange"
              :disabled="index > 1"
              :popper-options="popperOptions"
            >
              <el-option
                v-for="(itm, idx) in logicList"
                :key="'filter_logicList_' + idx"
                :label="itm.label"
                :value="itm.value"
              ></el-option>
            </el-select>
          </template>

          <el-select
            class="item"
            v-model="item.key"
            placeholder="请选择"
            :popper-options="popperOptions"
            @change="changeColumnHandler(item)"
            :filterable="true"
          >
            <el-option
              v-for="(itm, idx) in originalTableColumns.filter(itm => itm.filter)"
              :key="'filter_search_' + idx"
              :label="itm.title"
              :value="itm.key"
            ></el-option>
          </el-select>
          <el-select
            class="item"
            v-model="item.operate"
            placeholder="请选择"
            :popper-options="popperOptions"
            @focus="operateList(item)"
          >
            <el-option
              v-for="(itm, idx) in selectedList[item.key] || []"
              :key="'filter_search_' + idx"
              :label="itm.label"
              :value="itm.value"
            ></el-option>
            <template #empty>暂无数据</template>
          </el-select>
          <component
            class="item"
            :is="`el-${componentType(item.key)}`"
            v-model="item.value"
            :popper-options="popperOptions"
            v-bind="componentProps(item.key)"
            @focus="valueList(item)"
          >
            <template v-if="componentType(item.key) === 'select'">
              <el-option
                v-for="(itm, idx) in selectedList[item.key + '_value'] || []"
                :key="'filter_search_' + idx"
                :label="itm.label"
                :value="itm.value"
              >
              </el-option>
            </template>
          </component>
          <el-icon class="del-icon" @click="removeFilter(index)"><Delete /></el-icon>
        </li>
      </ul>
      <el-button type="text" :icon="Plus" @click="addFilter">新增筛选条件</el-button>
    </div>

    <div class="search-filter-footer">
      <span class="reset" @click="resetHandler">重置</span>
      <div class="options">
        <el-button @click="close" type="text">取消</el-button>
        <el-button type="primary" @click="saveHandler">确认</el-button>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, inject, toRaw } from "vue";
import { Plus, Close, Delete } from "@element-plus/icons-vue";
import { ElButton, ElIcon, ElSelect, ElOption } from "element-plus";
import { useData } from "@table/hooks/useData";
import { TableColumn } from "@table/interface";
import { useSearch } from "@table/hooks/useSearch";
import { useKeyValueStore } from "@/hooks/useKeyValueStore";
import { SearchCondition, SearchOptions } from "../interface";
import { logicList } from "@table/constant";
const { save } = useSearch();
const emits = defineEmits(["close"]);
const { setValue } = useKeyValueStore();

const {
  searchOptions: originalSearchOptions,
  originalTableColumns,
  copySearchOptions,
  eventBus,
  setCurrentPagination
} = useData();

const searchOptions = ref<SearchOptions>(copySearchOptions());

// 自定义 modifiers
const clickStopModifier = {
  name: "clickStop",
  enabled: true,
  phase: "afterWrite",
  fn({ state }) {
    const popperElement = state.elements.popper;
    popperElement.addEventListener("click", event => {
      event.stopPropagation();
    });
  }
};
// 在组件中使用
const popperOptions = {
  modifiers: [clickStopModifier]
};

// 所有的下拉
const selectedList = inject("selectedList");

// 方法
// 切换菜单清除选项值
const changeColumnHandler = (item: any) => {
  const obj: any = originalTableColumns.value.find((itm: TableColumn) => itm.key === item.key);
  item.value = "";
  item.operate = "";
  item.table = obj.tableName;
};

// 组件类型
const componentType = (key: string) => {
  return originalTableColumns.value.find((itm: TableColumn) => itm.key === key)?.filter?.type || "input";
};
// 组件属性
const componentProps = (key: string) => {
  return originalTableColumns.value.find((itm: TableColumn) => itm.key === key)?.filter?.attribute || {};
};
// 下拉数据
const operateList = async (item: SearchCondition) => {
  if (selectedList.value[item.key] && selectedList.value[item.key].length) return;
  const { operator, fieldOperate } = originalTableColumns.value.find((itm: TableColumn) => itm.key === item.key)?.filter as any;
  if (!fieldOperate) return;
  const data = operator && (await operator(fieldOperate));
  selectedList.value[item.key] = data || [];
};
// 值下拉
const valueList = async (item: SearchCondition) => {
  const key = item.key + "_value";
  if (selectedList.value[key] && selectedList.value[key].length) return;
  const { value, fieldValue } = originalTableColumns.value.find((itm: TableColumn) => itm.key === item.key)?.filter as any;
  if (!value) return;
  const data = value && (await value(fieldValue));
  selectedList.value[key] = data || [];
};
// 切换逻辑
const logicChange = (val: any) => {
  searchOptions.value.condition.forEach((itm: SearchCondition) => {
    itm.logic = val;
  });
};
const addFilter = () => {
  const logic = searchOptions.value.condition.length > 1 ? searchOptions.value.condition[1]["logic"] : "AND";
  const condition: SearchCondition = {
    logic,
    key: "",
    operate: "",
    value: "",
    table: ""
  };
  searchOptions.value.condition.push(condition);
};

const removeFilter = (index: number) => {
  searchOptions.value.condition.splice(index, 1);
};
const saveHandler = () => {
  // 过滤 空筛选
  searchOptions.value.condition = searchOptions.value.condition.filter(
    (itm: SearchCondition) => itm.operate && itm.value && itm.key
  );
  originalSearchOptions.value = searchOptions.value;
  setValue("orderTableFilterSelectList", toRaw(selectedList.value));
  save();
  close();
  setCurrentPagination();
  eventBus.emit("refresh");
};

const resetHandler = () => {
  searchOptions.value = copySearchOptions();
};
const close = () => {
  emits("close");
};
</script>
<style lang="scss" scoped>
.search-filter {
  width: 798px;
  max-height: 48vh;
  background: #ffffff;
  border-radius: 0.25rem;
  box-shadow: 0 0 16px #00000014;
  &-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 56px;
    padding: 0 32px;
    font-size: 16px;
    color: #000000;
  }
  &-body {
    max-height: 30vh;
    padding: 8px 32px 0;
    overflow-y: auto;
  }
  &-list {
    display: flex;
    flex-flow: column nowrap;
    gap: 15px;
    padding: 0;
    margin-bottom: 15px;
    li {
      display: flex;
      gap: 15px;
      align-items: center;
      flex: 1;
      .item {
        box-sizing: border-box;
        flex: 1;
        font-size: 14px;
      }
      :deep(.item) {
        flex: 1;
      }
      .dt {
        text-indent: 12px;
      }
    }
    .del-icon {
      flex: 0 0 16px;
      cursor: pointer;
      :hover {
        color: $primary-color;
      }
    }
  }
  &-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 32px;
    padding: 16px 32px;
    .reset {
      padding: 6px 10px;
      color: $primary-color;
      cursor: pointer;
    }
    .options {
      display: flex;
    }
  }
}
.pointer {
  cursor: pointer;
}
</style>
